// utils/api.js
// API 请求工具

const { showError, getStorage } = require('./util.js')
const { LoadingManager, ErrorHandler, CacheManager, PerformanceMonitor } = require('./performance.js')
const { getApiBaseUrl, isMockMode, shouldBypassTokenCheck, shouldSkipLoginRedirect } = require('./config.js')
const { mockRequest, mockUpload, showMockModeNotice } = require('./mock-api.js')

// API 基础配置
const API_BASE_URL = getApiBaseUrl() // 从配置文件获取
const REQUEST_TIMEOUT = 10000
const RETRY_TIMES = 3
const RETRY_DELAY = 1000

// 显示模拟模式提示
showMockModeNotice()

/**
 * 增强的网络请求
 */
const request = (options) => {
  const {
    url,
    method = 'GET',
    data = {},
    header = {},
    timeout = REQUEST_TIMEOUT,
    useCache = false,
    cacheKey = null,
    showLoading = false,
    loadingTitle = '加载中...',
    retryTimes = RETRY_TIMES
  } = options

  // 如果是模拟模式，使用模拟API
  if (isMockMode()) {
    return mockRequest(url, method, data)
  }

  const startTime = Date.now()
  const requestId = `${method}_${url}_${startTime}`

  // 显示加载状态
  if (showLoading) {
    LoadingManager.show(requestId, { title: loadingTitle })
  }

  // 检查缓存
  if (useCache && method === 'GET' && cacheKey) {
    const cachedData = CacheManager.get(cacheKey)
    if (cachedData) {
      if (showLoading) {
        LoadingManager.hide(requestId)
      }
      return Promise.resolve(cachedData)
    }
  }

  return new Promise((resolve, reject) => {
    const performRequest = (remainingRetries) => {
      // 获取用户token
      const token = getStorage('userToken')

      // 设置请求头
      const requestHeader = {
        'Content-Type': 'application/json',
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'X-Request-ID': requestId,
        'X-Timestamp': Date.now().toString(),
        ...header
      }

      // 如果有token且未跳过认证，添加到请求头
      if (token && !shouldBypassTokenCheck()) {
        requestHeader['Authorization'] = `Bearer ${token}`
      } else if (shouldBypassTokenCheck()) {
        console.warn('🚫 认证已屏蔽，跳过Token验证')
      }

      wx.request({
        url: `${API_BASE_URL}${url}`,
        method,
        data,
        header: requestHeader,
        timeout,
        success: (res) => {
          const endTime = Date.now()

          // 记录性能数据
          PerformanceMonitor.recordApiResponse(url, startTime, endTime)

          const { statusCode, data: responseData } = res

          if (statusCode === 200) {
            // 请求成功
            if (responseData.code === 0) {
              // 缓存数据
              if (useCache && method === 'GET' && cacheKey) {
                CacheManager.set(cacheKey, responseData.data)
              }

              if (showLoading) {
                LoadingManager.hide(requestId)
              }

              resolve(responseData.data)
            } else {
              // 业务错误
              const error = {
                type: 'business',
                code: responseData.code,
                message: responseData.message || '请求失败',
                data: responseData
              }

              if (showLoading) {
                LoadingManager.hide(requestId)
              }

              ErrorHandler.handle(error, { url, method, data, requestId })
              reject(error)
            }
          } else {
            // HTTP错误
            const error = {
              type: 'http',
              statusCode,
              message: `HTTP ${statusCode}`,
              response: res
            }

            if (statusCode === 401) {
              // 未授权，检查是否跳过登录重定向
              if (!shouldSkipLoginRedirect()) {
                wx.removeStorageSync('userToken')
                wx.removeStorageSync('userInfo')
                wx.redirectTo({
                  url: '/pages/login/login'
                })
                error.message = '登录已过期'
              } else {
                console.warn('🚫 认证已屏蔽，跳过登录重定向')
                error.message = '认证失败（已屏蔽）'
              }
            }

            if (showLoading) {
              LoadingManager.hide(requestId)
            }

            ErrorHandler.handle(error, { url, method, data, requestId })
            reject(error)
          }
        },
        fail: (err) => {
          console.error('网络请求失败:', err)

          // 重试逻辑
          if (remainingRetries > 0 && this.shouldRetry(err)) {
            console.log(`请求失败，${RETRY_DELAY}ms后重试，剩余重试次数: ${remainingRetries - 1}`)
            setTimeout(() => {
              performRequest(remainingRetries - 1)
            }, RETRY_DELAY)
            return
          }

          if (showLoading) {
            LoadingManager.hide(requestId)
          }

          const error = {
            type: 'network',
            message: '网络连接失败',
            originalError: err
          }

          ErrorHandler.handle(error, { url, method, data, requestId })
          reject(error)
        }
      })
    }

    performRequest(retryTimes)
  })
}

/**
 * 判断是否应该重试
 */
const shouldRetry = (error) => {
  // 网络错误和超时错误可以重试
  return error.errMsg && (
    error.errMsg.includes('timeout') ||
    error.errMsg.includes('fail') ||
    error.errMsg.includes('network')
  )
}

/**
 * GET 请求
 */
const get = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'GET',
    data,
    useCache: options.useCache || false,
    cacheKey: options.cacheKey,
    showLoading: options.showLoading || false,
    loadingTitle: options.loadingTitle,
    ...options
  })
}

/**
 * POST 请求
 */
const post = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    showLoading: options.showLoading || false,
    loadingTitle: options.loadingTitle,
    ...options
  })
}

/**
 * PUT 请求
 */
const put = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    showLoading: options.showLoading || false,
    loadingTitle: options.loadingTitle,
    ...options
  })
}

/**
 * DELETE 请求
 */
const del = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'DELETE',
    data,
    showLoading: options.showLoading || false,
    loadingTitle: options.loadingTitle,
    ...options
  })
}

/**
 * 增强的文件上传
 */
const uploadFile = (filePath, options = {}) => {
  // 如果是模拟模式，使用模拟上传
  if (isMockMode()) {
    return mockUpload(filePath, options)
  }

  const {
    fileName = 'file',
    url = '/upload',
    showProgress = false,
    maxSize = 10 * 1024 * 1024, // 10MB
    allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
  } = options

  return new Promise((resolve, reject) => {
    // 检查文件大小
    wx.getFileInfo({
      filePath,
      success: (fileInfo) => {
        if (fileInfo.size > maxSize) {
          const error = new Error('文件大小超过限制')
          ErrorHandler.handle(error)
          reject(error)
          return
        }

        const token = getStorage('userToken')
        const startTime = Date.now()

        const uploadTask = wx.uploadFile({
          url: `${API_BASE_URL}${url}`,
          filePath,
          name: fileName,
          header: {
            'Authorization': token ? `Bearer ${token}` : ''
          },
          success: (res) => {
            const endTime = Date.now()
            PerformanceMonitor.recordApiResponse(url, startTime, endTime)

            try {
              const data = JSON.parse(res.data)
              if (data.code === 0) {
                resolve(data.data)
              } else {
                const error = new Error(data.message || '上传失败')
                ErrorHandler.handle(error)
                reject(error)
              }
            } catch (e) {
              const error = new Error('上传响应解析失败')
              ErrorHandler.handle(error)
              reject(error)
            }
          },
          fail: (err) => {
            console.error('文件上传失败:', err)
            const error = { ...err, message: '文件上传失败' }
            ErrorHandler.handle(error)
            reject(error)
          }
        })

        // 显示上传进度
        if (showProgress) {
          uploadTask.onProgressUpdate((res) => {
            console.log('上传进度:', res.progress + '%')
            // 可以在这里更新UI进度条
          })
        }
      },
      fail: (error) => {
        ErrorHandler.handle(error)
        reject(error)
      }
    })
  })
}

/**
 * 批量请求
 */
const batchRequest = (requests) => {
  const promises = requests.map(req => {
    const { method = 'GET', ...options } = req
    return request({ method, ...options })
  })

  return Promise.allSettled(promises)
}

/**
 * 取消请求
 */
const cancelRequest = (requestId) => {
  // 小程序原生不支持取消请求，这里只是示例
  console.log('取消请求:', requestId)
}

/**
 * 获取缓存的数据
 */
const getCachedData = (cacheKey) => {
  return CacheManager.get(cacheKey)
}

/**
 * 清除缓存
 */
const clearCache = (cacheKey) => {
  if (cacheKey) {
    CacheManager.remove(cacheKey)
  } else {
    CacheManager.clearAll()
  }
}

/**
 * 查询用户档案
 * @param {Object} queryParams - 查询参数
 * @param {Array} queryParams.userNumList - 用户编号列表
 * @param {string} queryParams.gender - 性别 "男"/"女"
 * @param {Object} queryParams.ageRange - 年龄范围
 * @param {number} queryParams.minHeight - 最低身高
 * @param {number} queryParams.maxWeight - 最高体重
 * @param {Object} queryParams.educationRange - 学历范围
 * @param {number} queryParams.minIncome - 最低收入
 * @param {string} queryParams.occupation - 职业
 * @param {boolean} queryParams.parentsHasPension - 父母是否有退休金
 * @returns {Promise} 返回用户档案查询结果
 */
const queryUserProfiles = (queryParams = {}, options = {}) => {
  // 打印请求参数
  console.log('=== 用户档案查询 API 请求 ===')
  console.log('🚀 API Endpoint: /matchmaking/userprofile/query')
  console.log('🌐 API Base URL:', getApiBaseUrl())
  console.log('🛠️ Mock Mode:', isMockMode() ? '✅ 开启' : '❌ 关闭 (使用真实API)')
  console.log('🚫 Authentication:', shouldBypassTokenCheck() ? '❌ 已屏蔽' : '✅ 开启')
  console.log('📄 Request Parameters:', JSON.stringify(queryParams, null, 2))
  console.log('⚙️ Request Options:', JSON.stringify(options, null, 2))

  return post('/matchmaking/userprofile/query', queryParams, {
    showLoading: options.showLoading || true,
    loadingTitle: options.loadingTitle || '查询用户中...',
    ...options
  }).then(response => {
    // 打印返回结果
    console.log('=== 用户档案查询 API 返回 ===')
    console.log('✅ Response Status: Success')
    console.log('🔄 Data Source:', isMockMode() ? '🧪 Mock Data' : '🌐 Real API Data')
    console.log('📈 Response Data:', JSON.stringify(response, null, 2))

    // 打印结果统计
    if (response && response.userprofileList) {
      console.log('📊 结果统计:')
      console.log(`  - 总用户数: ${response.totalNum || 0}`)
      console.log(`  - 返回用户数: ${response.userprofileList.length}`)

      // 打印前3个用户的详细信息
      if (response.userprofileList.length > 0) {
        console.log('👥 用户示例（前3个）:')
        response.userprofileList.slice(0, 3).forEach((user, index) => {
          console.log(`  用户 ${index + 1}:`, {
            userNum: user.userNum,
            name: user.name,
            gender: user.gender,
            age: user.age,
            height: user.height,
            education: user.education,
            occupation: user.occupation,
            maritalStatus: user.maritalStatus,
            annualIncome: user.assets?.annualIncome,
            isPartyMember: user.isPartyMember
          })
        })
      }
    }

    console.log('=== 用户档案查询 API 结束 ===')
    return response
  }).catch(error => {
    // 打印错误信息
    console.log('=== 用户档案查询 API 错误 ===')
    console.error('❌ Error Type:', error.type || 'unknown')
    console.error('❌ Error Message:', error.message || error)
    console.error('❌ Error Details:', error)
    console.log('=== 用户档案查询 API 错误结束 ===')
    throw error
  })
}

/**
 * 查询用户详细信息
 * @param {Array<number>} userNumList - 用户编号列表
 * @param {Object} options - 请求选项
 * @returns {Promise} - 返回用户详细信息
 */
const queryUserAllInfo = (userNumList = [], options = {}) => {
  console.log('=== 用户详细信息查询 API 请求 ===')
  console.log('🚀 API Endpoint: /matchmaking/userprofile/allInfo')
  console.log('🌐 API Base URL:', getApiBaseUrl())
  console.log('📋 用户编号列表:', userNumList)
  console.log('🚫 Authentication:', shouldBypassTokenCheck() ? '❌ 已屏蔽' : '✅ 开启')

  const requestData = {
    userNumList: userNumList
  }

  console.log('📤 请求数据:', JSON.stringify(requestData, null, 2))

  return post('/matchmaking/userprofile/allInfo', requestData, {
    showLoading: options.showLoading !== false,
    loadingTitle: options.loadingTitle || '获取用户详情中...',
    ...options
  }).then(data => {
    console.log('=== 用户详细信息查询 API 响应 ===')
    console.log('📈 API 返回数据:', JSON.stringify(data, null, 2))

    if (data && data.userInfoList) {
      console.log('✅ 成功获取用户详细信息:')
      console.log(`   - 用户数量: ${data.userInfoList.length}`)

      // 打印前3个用户的详细信息
      data.userInfoList.slice(0, 3).forEach((user, index) => {
        console.log(`   用户 ${index + 1} 详情:`, {
          userNum: user.userNum,
          name: user.name,
          gender: user.gender,
          age: user.age,
          education: user.education,
          occupation: user.occupation,
          annualIncome: user.assets?.annualIncome,
          car: user.assets?.car,
          house: user.assets?.house,
          requirements: {
            ageRange: user.ageRange,
            minHeight: user.minHeight,
            maxWeight: user.maxWeight,
            minIncome: user.minIncome,
            occupationRequire: user.occupationRequire
          }
        })
      })
    }

    console.log('=== 用户详细信息查询结束 ===')
    return data
  }).catch(error => {
    console.log('=== 用户详细信息查询错误 ===')
    console.error('❌ 错误类型:', error.type || 'unknown')
    console.error('❌ 错误消息:', error.message || error)
    console.error('❌ 错误详情:', error)
    console.log('⚠️ 请求参数:', JSON.stringify(requestData, null, 2))
    console.log('=== 用户详细信息查询错误结束 ===')
    throw error
  })
}

/**
 * 同步用户资料
 * @param {Object} userProfileData - 用户资料数据
 * @param {number} userProfileData.userNum - 用户编号
 * @param {string} userProfileData.name - 姓名
 * @param {string} userProfileData.gender - 性别（男/女）
 * @param {number} userProfileData.height - 身高（厘米）
 * @param {number} userProfileData.weight - 体重（斤）
 * @param {string} userProfileData.birthDate - 生日 (YYYY-MM-DD)
 * @param {string} userProfileData.maritalStatus - 婚姻状态
 * @param {Object} userProfileData.assets - 资产情况
 * @param {string} userProfileData.education - 教育经历
 * @param {string} userProfileData.occupation - 职业
 * @param {boolean} userProfileData.isPartyMember - 是否党员
 * @param {string} userProfileData.hometown - 籍贯
 * @param {string} userProfileData.currentResidence - 常住地
 * @param {Object} userProfileData.familyMembers - 家庭成员
 * @param {Object} options - 请求选项
 * @returns {Promise} - 返回同步结果
 */
const syncUserProfile = (userProfileData = {}, options = {}) => {
  console.log('=== 用户资料同步 API 请求 ===')
  console.log('🚀 API Endpoint: /matchmaking/userprofile/sync')
  console.log('🌐 API Base URL:', getApiBaseUrl())
  console.log('🚫 Authentication:', shouldBypassTokenCheck() ? '❌ 已屏蔽' : '✅ 开启')

  // 数据验证和预处理
  const requestData = {
    userNum: userProfileData.userNum || 0,
    name: userProfileData.name || '',
    gender: userProfileData.gender || '',
    height: parseInt(userProfileData.height) || 0,
    weight: parseInt(userProfileData.weight) || 0,
    birthDate: userProfileData.birthDate || '',
    maritalStatus: userProfileData.maritalStatus || '',
    assets: userProfileData.assets || {
      annualIncome: 0,
      car: '',
      house: ''
    },
    education: userProfileData.education || '',
    occupation: userProfileData.occupation || '',
    isPartyMember: Boolean(userProfileData.isPartyMember),
    hometown: userProfileData.hometown || '',
    currentResidence: userProfileData.currentResidence || '',
    familyMembers: userProfileData.familyMembers || {
      familyType: '',
      fatherDetail: { age: 0, desc: '' },
      motherDetail: { age: 0, desc: '' },
      otherDetail: []
    },
    createUser: userProfileData.createUser || 'miniprogram',
    modifyUser: userProfileData.modifyUser || 'miniprogram'
  }

  console.log('📤 请求数据:', JSON.stringify(requestData, null, 2))

  return post('/matchmaking/userprofile/sync', requestData, {
    showLoading: options.showLoading !== false,
    loadingTitle: options.loadingTitle || '保存资料中...',
    ...options
  }).then(data => {
    console.log('=== 用户资料同步 API 响应 ===')
    console.log('📈 API 返回数据:', JSON.stringify(data, null, 2))

    if (data && data.userNum) {
      console.log('✅ 成功同步用户资料:')
      console.log(`   - 用户编号: ${data.userNum}`)
      console.log(`   - 同步的字段数: ${Object.keys(requestData).length}`)
    }

    console.log('=== 用户资料同步结束 ===')
    return data
  }).catch(error => {
    console.log('=== 用户资料同步错误 ===')
    console.error('❌ 错误类型:', error.type || 'unknown')
    console.error('❌ 错误消息:', error.message || error)
    console.error('❌ 错误详情:', error)
    console.log('⚠️ 请求参数:', JSON.stringify(requestData, null, 2))
    console.log('=== 用户资料同步错误结束 ===')
    throw error
  })
}

module.exports = {
  request,
  get,
  post,
  put,
  del,
  uploadFile,
  batchRequest,
  cancelRequest,
  getCachedData,
  clearCache,
  queryUserProfiles,
  queryUserAllInfo,
  syncUserProfile
}